package org.baojie.raft.connector.server.initializer;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import org.baojie.raft.box.Box;
import org.baojie.raft.connector.server.handler.RaftServerHandler;

public class ServerChannelInit extends ChannelInitializer<SocketChannel> {

    private final Box box;

    public ServerChannelInit(Box box) {
        this.box = box;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        // Decoders
        ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4));
        ch.pipeline().addLast("decoder", new ByteArrayDecoder());
        // Encoder
        ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(4));
        ch.pipeline().addLast("encoder", new ByteArrayEncoder());
        ch.pipeline().addLast(new RaftServerHandler(box));
    }

}